package org.nimi317.web_gis.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import org.nimi317.web_gis.form.post.RolePermissionPost;
import org.nimi317.web_gis.form.post.RolePost;
import org.nimi317.web_gis.entity.R;
import org.nimi317.web_gis.entity.Role;
import org.nimi317.web_gis.service.IPermissionService;
import org.nimi317.web_gis.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author thunderobot
 */
@RestController
@RequestMapping("roles")
@SaCheckLogin
@SaCheckRole("admin")
public class RoleController {

    private final IRoleService service;

    private final IPermissionService permissionService;

    public RoleController(IRoleService service, IPermissionService permissionService) {
        this.service = service;
        this.permissionService = permissionService;
    }

    @GetMapping
    public R<?> getRoles() {
        return R.ok(service.getAllRoles());
    }

    @PostMapping
    public R<?> addRole(@RequestBody @Validated RolePost rolePost) {
        Role role = new Role();
        BeanUtils.copyProperties(rolePost, role);
        service.createRole(role);
        return R.ok("添加角色成功");
    }


    @PutMapping
    public R<?> updateRole(@RequestBody @Validated RolePost rolePost) {
        Role role = new Role();
        BeanUtils.copyProperties(rolePost, role);
        service.updateRole(role);
        return R.ok("更新角色成功");
    }


    @DeleteMapping("{id}")
    public R<?> deleteRole(@PathVariable Integer id) {
        service.deleteRole(id);
        return R.ok("删除角色成功");
    }

    @PostMapping("associate")
    public R<?> associatePermission(@RequestBody RolePermissionPost rolePermissionPost) {
        permissionService.addRolePermission(rolePermissionPost.getRoleId(), rolePermissionPost.getPermissionIds());
        return R.ok("分配权限成功");
    }
}

